<?php
/**
 * @version $Id: component.php 5426 2006-10-11 04:38:35Z Jinx $
 * @package Joomla
 * @subpackage Config
 * @copyright Copyright (C) 2005 - 2006 Open Source Matters. All rights reserved.
 * @license GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant to the
 * GNU General Public License, and as distributed it includes or is derivative
 * of works licensed under the GNU General Public License or other free or open
 * source software licenses. See COPYRIGHT.php for copyright notices and
 * details.
 */

jimport( 'joomla.application.component.controller' );

/**
 * Note: this view is intended only to be opened in a popup
 * @package Joomla
 * @subpackage Config
 */
class HotelsController extends JController
{

	/**
	 * Custom Constructor
	 */
	//DEVNOTE: register task - Register (map) a task to a method in the class
	//function registerTask( $task, $method )
	function __construct( $default = array()){			
		parent::__construct( $default );	
	}


	/**
	 * Cancel operation
	 */
//	function cancel()
//	{
//		$this->setRedirect( 'index.php' );
//	}
//	
	function display() {
//		echo JRequest::getCmd('task');
		switch(JRequest::getCmd('task')){
			case 'cancel':
				$this->cancel();
				break;
			case 'save':
			case 'apply':
				$this->save();
				break;
			case 'add':
				$this->hotels( false );				
				break;
			case 'edit':
				$this->hotels( true );				
				break;
			case 'publish':
			case 'unpublish':
				$this->publish();				
				break;
			default:
				$this->listHotels();
				break;
		}	
  	}
  	function listHotels(){  		
  		
  		global $mainframe;
  		
  		$db =& JFactory::getDBO();
  		$model = &JModel::getInstance( 'HotelsComponentModel' );	  	
	   	$view = new DefaultComponentView( );
  		
	   		   	
  		$context			= 'com_banners.banner.list.';
		$filter_order		= $mainframe->getUserStateFromRequest( $context.'filter_order',		'filter_order',		'h.hotel_name',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $context.'filter_order_Dir',	'filter_order_Dir',	'',			'word' );
		$filter_catid		= $mainframe->getUserStateFromRequest( $context.'filter_catid',		'filter_catid',		'',			'int' );
		$filter_state		= $mainframe->getUserStateFromRequest( $context.'filter_state',		'filter_state',		'',			'word' );
		$search				= $mainframe->getUserStateFromRequest( $context.'search',			'search',			'',			'string' );
		if (strpos($search, '"') !== false) {
			$search = str_replace(array('=', '<'), '', $search);
		}
		$search = JString::strtolower($search);

		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $context.'limitstart', 'limitstart', 0, 'int' );
  		  		  	

	   	if ($search) {
			$where[] = 'LOWER(h.hotel_name) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}

		$where		= count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '';
	   	echo $where; 
		$orderby	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir .', h.ordering';

		$query = 'SELECT COUNT(*)'
		. ' FROM #__hotels AS h'
//		. ' LEFT JOIN #__categories AS cc ON cc.id = b.catid'
		. $where
		;
		$db->setQuery( $query );
		$total = $db->loadResult();

		jimport('joomla.html.pagination');
		$pageNav = new JPagination( $total, $limitstart, $limit );
		
		$query = 'SELECT h.* '
		. ' FROM #__hotels AS h '		
		. $where
		. $orderby
		;
//		echo $query;
		$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
		$rows = $db->loadObjectList();
				
		// build list of categories
		$javascript		= 'onchange="document.adminForm.submit();"';
	   	
		// table ordering
		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;

		// search filter
		$lists['search']= $search;
		
	   	$view->display($rows, $pageNav, $lists);
  	}
  	function hotels( $edit ){
  		global $mainframe;
  		
  		$db		=& JFactory::getDBO();
		$user	=& JFactory::getUser();

		if ($this->_task == 'edit') {
			$cid	= JRequest::getVar('cid', array(0), 'method', 'array');
			$cid	= array((int) $cid[0]);
		} else {
			$cid	= array( 0 );
		}  		

  		$lists = array();

		$row =& JTable::getInstance('hotel', 'Table');
	
		$row->load( $cid[0] );

		if ($cid[0]) {
			$row->checkout( $user->get('id') );
		}
	  	// 	Build Client select list
		$sql = 'SELECT * '
		. ' FROM #__hotels'
		. ' WHERE id = '.$cid[0]
		;
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_hotels' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}
		$row = $db->loadObject();
		
		// Imagelist
		$javascript			= 'onchange="changeDisplayImage();"';
		$directory			= '/images/hotels';
		$lists['imageurl']	= JHTML::_('list.images',  'imageurl', $row->imageurl, $javascript, $directory, "bmp|gif|jpg|png|swf"  );
		
	   	$view = new DefaultComponentView( );	   		   	
	   	$view->hotels( $row, $lists );
  	}
	function cancel(){
//		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$this->setRedirect( 'index.php?option=com_hotels' );

	}
	
	/**
	 * Save method
	 */ 
	function save()
	{
		global $mainframe;
		
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		
		//$this->setRedirect( 'index.php?option=com_hotels' );

		// Initialize variables
		$db =& JFactory::getDBO();
		$row =& JTable::getInstance('hotel', 'Table');		
		$post	= JRequest::get( 'post' );
		$task = JRequest::getCmd( 'task' );
		// fix up special html fields
		$post['address'] = JRequest::getVar( 'address', '', 'post', 'string', JREQUEST_ALLOWRAW );				
		
		if (!$row->bind( $post )) {
			return JError::raiseWarning( 500, $row->getError() );
		}

		if (!$row->check()) {
			return JError::raiseWarning( 500, $row->getError() );
		}

		// if new item order last in appropriate group
		if (!$row->id)
		{
			$where = 'id = '.(int) $row->cid;
			$row->ordering = $row->getNextOrder( $where );
		}

		if (!$row->store()) {
			return JError::raiseWarning( 500, $row->getError() );
		}
		$row->checkin();

		switch ($task)
		{
			case 'apply':
				$link = 'index.php?option=com_hotels&task=edit&cid[]='. $row->id ;
				break;

			case 'save':
			default:
				$link = 'index.php?option=com_hotels';
				break;
		}

		$this->setRedirect( $link, JText::_( 'Item Saved' ) );
	}
	
	function publish(){
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$this->setRedirect( 'index.php?option=com_hotels' );

		// Initialize variables
		$db			=& JFactory::getDBO();
		$user		=& JFactory::getUser();
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$task		= JRequest::getCmd( 'task' );
		$publish	= ($task == 'publish');
		$n			= count( $cid );

		if (empty( $cid )) {
			return JError::raiseWarning( 500, JText::_( 'No items selected' ) );
		}

		JArrayHelper::toInteger( $cid );
		$cids = implode( ',', $cid );

		$query = 'UPDATE #__hotels'
		. ' SET published = ' . (int) $publish
		. ' WHERE id IN ( '. $cids.'  )'
		. ' AND ( checked_out = 0 OR ( checked_out = ' .(int) $user->get('id'). ' ) )'
		;
//		echo $query;exit;
		$db->setQuery( $query );
		if (!$db->query()) {
			return JError::raiseWarning( 500, $db->getError() );
		}
		$this->setMessage( JText::sprintf( $publish ? 'Items published' : 'Items unpublished', $n ) );
	}
	function remove()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$this->setRedirect( 'index.php?option=com_hotels' );

		// Initialize variables
		$db		=& JFactory::getDBO();
		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$n		= count( $cid );
		JArrayHelper::toInteger( $cid );

		if ($n)
		{
			$query = 'DELETE FROM #__hotels'
			. ' WHERE id = ' . implode( ' OR id = ', $cid )
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				JError::raiseWarning( 500, $db->getError() );
			}
		}

		$this->setMessage( JText::sprintf( 'Items removed', $n ) );
	}
	
	function saveOrder()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$this->setRedirect( 'index.php?option=com_hotels' );

		// Initialize variables
		$db			=& JFactory::getDBO();
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$order		= JRequest::getVar( 'order', array(), 'post', 'array' );
		$row		=& JTable::getInstance('hotel', 'Table');
		$total		= count( $cid );
		$conditions	= array();

		if (empty( $cid )) {
			return JError::raiseWarning( 500, JText::_( 'No items selected' ) );
		}

		// update ordering values
		for ($i = 0; $i < $total; $i++)
		{
			$row->load( (int) $cid[$i] );
			if ($row->ordering != $order[$i])
			{
				$row->ordering = $order[$i];
				if (!$row->store()) {
					return JError::raiseError( 500, $db->getErrorMsg() );
				}
				// remember to reorder this category
				$condition = 'id = '.(int) $row->cid;
				$found = false;
				foreach ($conditions as $cond) {
					if ($cond[1] == $condition)
					{
						$found = true;
						break;
					}
				}
				if (!$found) {
					$conditions[] = array ( $row->id, $condition );
				}
			}
		}

		// execute reorder for each category
		foreach ($conditions as $cond)
		{
			$row->load( $cond[0] );
			$row->reorder( $cond[1] );
		}
//		$row->reorder();
		// Clear the component's cache
		$cache =& JFactory::getCache('com_hotels');
		$cache->clean();

		$this->setMessage( JText::_('New ordering saved') );
	}
}
?>
